<?php

define( 'ADD_DEVICE_ACTION', 1 );
define( 'DELETE_DEVICE_ACTION', 2 );
define( 'MODIFY_DEVICE_ACTION', 3 );

define( 'LIST_DEVICES_RECENT', 4 );
define( 'LIST_DEVICES_IN', 5 );
define( 'LIST_DEVICES_OUT', 6 );

define( 'RENT_DEVICE', 7 );
define( 'RETURN_DEVICE', 8 );

define( 'GET_DEVICE_BY_ID', 9 );
define( 'AJAX_USER_SEARCH', 10 );


define( 'XML_ROOT', '<?xml version="1.0" encoding="UTF-8"?><hk-rent></hk-rent>' );

//QUERY STATUSES

define( 'ALL_OK', 1 );
define( 'ALL_FAILED', 0 );

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once( 'device-manager.php' );
require_once( 'rent-manager.php' );
require_once( 'utils.php' );

/**
 * This is a TLU Haapsalu College...
 *
 * REST WebService for ...
 *
 * @author Raido Kuli @ 2012
 */
 

if ( isSet( $_REQUEST ) ) {
	//TODO implement security, QR code inital setup like google auth
	
	$deviceManager = new DeviceManager();
	switch( getServiceAction() ) {
		case ADD_DEVICE_ACTION:
			$deviceManager->add();
			break;
		CASE MODIFY_DEVICE_ACTION:
			$deviceManager->edit();
			break;
		case DELETE_DEVICE_ACTION:
			$deviceManager->delete();
			break;
		case LIST_DEVICES_RECENT:
			echo $deviceManager->asXML( $deviceManager->getRecentDevices() );
			break;
		case LIST_DEVICES_IN:
			echo $deviceManager->asXML( $deviceManager->getDevicesInStorage() );
			break;
		case LIST_DEVICES_OUT:
			echo $deviceManager->asXML( $deviceManager->getDevicesOutStorage() );
			break;
		case GET_DEVICE_BY_ID:
			//TODO SECURITY
			$device_id = Utils::getRequestDeviceID();
			if ( $device_id ) {
				$device = $deviceManager->getDeviceByID( $device_id );
				if ( $device ) {
					echo $device->getJSON();
				}
			}
			break;
		/* In & out devices */
		case RENT_DEVICE:
			$contract_id = $deviceManager->rentDevice();
			if ( $contract_id ) {
				header( 'Location: contract-pdf.php?id='.$contract_id );
				exit;
			}
			break;
		case RETURN_DEVICE:
			$deviceManager->returnDevice();
			break;
		case AJAX_USER_SEARCH:
			if ( isSet( $_GET['term'] ) ) {
				$rentManager = new RentManager();
				$rentManager->getUserLike( $_GET['term'] ); //This returns JSON
			}
			break;
	}
}

function getServiceAction() {
	if ( isSet( $_REQUEST['service_action'] ) ) {
		return intval( $_REQUEST['service_action'] );
	}
	return false;
}
?>